<template>
  <div class="productManager">
    <div class="breadcrumb">
      <el-icon>
        <Location />
      </el-icon>
      <el-breadcrumb separator="/">
        <el-breadcrumb-item>用户管理</el-breadcrumb-item>
        <el-breadcrumb-item>用户管理员</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
 
    <div class="content">
      <div class="top">
        <div style="display:flex;">
          <el-input v-model="account" class="w-50 m-2" placeholder="请输入账户" :prefix-icon="Search"></el-input>
          <el-button type="primary" @click="togetProductManager()">确认</el-button>
        </div>
        <div>
          <el-button type="primary" @click="dialogVisible = true; isEdit = false;">添加用户管理员</el-button>
        </div>
      </div>

      <el-table :data="tableData" border style="width: 100%">
        <el-table-column type="index" width="50" />
        <el-table-column prop="account" label="账户" />
        <el-table-column prop="name" label="姓名" />
        <el-table-column prop="department" label="部门" />
        <el-table-column prop="email" label="邮箱" />
        <el-table-column label="操作" width="140">
          <template #default="scope">
            <el-button size="small" type="success" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
            <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <el-pagination
        :current-page="pageNum"
        :page-size="pageSize"
        :page-sizes="[10, 20, 30, 40]"
        :background="background"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <el-dialog draggable
      v-model="dialogVisible"
      :title="(isEdit ? '修改' : '新建') + '用户管理员'"
      width="30%"
      @close="dialogVisibleClose(ruleFormRef)"
    >
      <el-form
        ref="ruleFormRef"
        :model="ruleForm"
        :rules="rules"
        label-width="120px"
        class="demo-ruleForm"
        status-icon
      >
        <el-form-item label="账户" prop="account">
          <el-input v-model="ruleForm.account" :disabled="isEdit" placeholder="账户" />
        </el-form-item>
        <el-form-item label="密码" prop="password" v-if="!isEdit">
          <el-input v-model="ruleForm.password" placeholder="密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="ruleForm.name" placeholder="姓名" />
        </el-form-item>
        <el-form-item label="性别" prop="sex">
          <el-select v-model="ruleForm.sex" placeholder="性别" style="width:100%">
            <el-option label="男" value="男" />
            <el-option label="女" value="女" />
          </el-select>
        </el-form-item>
        <el-form-item label="email" prop="email">
          <el-input v-model="ruleForm.email" placeholder="email" />
        </el-form-item>
        <el-form-item label="部门" prop="department">
          <el-select v-model="ruleForm.department" placeholder="部门" style="width:100%">
            <!-- <el-option label="科技部" value="科技部" /> -->
            <el-option :label="item.name" :value="item.name" v-for="item in departmentList" :key="item.id" />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
          <el-button type="primary" @click="submitForm(ruleFormRef)">确认</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>


<script setup>
import { ref, reactive, toRefs, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import {
  addProductManager,
  getProductManager,
  deleteProductManager,
  modifyProductManager,
  getDepartment
} from "@/api/user";
import {
  addOperationLog
} from "@/api/log"; 
import { useRouter } from "vue-router";
const router = useRouter();

// 调用store树中内容需要引入
import { useStore } from "vuex";
// 获取store
const store = useStore();

import {
  Document,
  Menu as IconMenu,
  Location,
  Setting,
  House,
  Message,
  Grid,
  Avatar,
  Position,
  ChatLineSquare,
  Notebook,
  UserFilled,
  User,
  Notification,
  ChatRound,
  Search
} from "@element-plus/icons-vue";
const tableData = ref([]);
const isEdit = ref(false);
const handleEdit = (index, row) => {
  console.log(index, row);
  isEdit.value = true;
  ruleForm.id = row.id;
  ruleForm.account = row.account;
  ruleForm.name = row.name;
  ruleForm.sex = row.sex;
  ruleForm.email = row.email;
  ruleForm.department = row.department;

  dialogVisible.value = true;
};
const handleDelete = (index, row) => {
  ElMessageBox.confirm(
    "是否去掉此用户的管理员职位? 删除后此用户将重新展现在用户列表中",
    "删除操作",
    {
      confirmButtonText: "确定",
      cancelButtonText: "取消",
      type: "warning"
    }
  )
    .then(() => {
      let query = {
        id: row.id
      };
      deleteProductManager(query).then(async res => {
        if (res.data.status != 0) {
          return ElMessage.error(res.data.message);
        }
        await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + row.id + '的用户管理员删除，删除之后恢复成普通用户',operation_level:"高级"});
        togetProductManager();
        ElMessage.success(res.data.message);
      });
    })
    .catch(() => {});
};

const dialogVisible = ref(false);
const ruleFormRef = ref();
const ruleForm = reactive({
  identity: "用户管理员",
  account: "",
  password: "",
  name: "",
  sex: "",
  email: "",
  department: ""
});

const rules = reactive({
  account: [{ required: true, message: "账户", trigger: "blur" }],
  password: [{ required: true, message: "账户", trigger: "blur" }],
  name: [{ required: true, message: "账户", trigger: "blur" }],
  sex: [{ required: true, message: "账户", trigger: "blur" }],
  email: [{ required: true, message: "账户", trigger: "blur" }],
  department: [{ required: true, message: "账户", trigger: "blur" }]
});

const submitForm = async formEl => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      if (isEdit.value) {
        let data = {
          id: ruleForm.id,
          name: ruleForm.name,
          sex: ruleForm.sex,
          email: ruleForm.email,
          department: ruleForm.department
        };
        modifyProductManager(data).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"对id是" + ruleForm.id + '的用户管理员修改',operation_level:"一般"});
          togetProductManager();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      } else {
        addProductManager(ruleForm).then(async res => {
          if (res.data.status != 0) {
            return ElMessage.error(res.data.message);
          }
          await addOperationLog({operation_person:localStorage.getItem("name"),operation_content:"添加了用户管理员",operation_level:"中级"});
          togetProductManager();
          ElMessage.success(res.data.message);
          dialogVisible.value = false;
        });
      }
    } else {
      console.log("error submit!", fields);
    }
  });
};

const dialogVisibleClose = formEl => {
  if (!formEl) return;
  formEl.resetFields();
};
const account = ref();
const total = ref(null);
const pageNum = ref(1);
const pageSize = ref(10);
const togetProductManager = () => {
  let query = {
    identity: "用户管理员",
    account: account.value,
    pageNum: pageNum.value,
    pageSize: pageSize.value
  };
  getProductManager(query).then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    // ElMessage.success(res.data.message);
    tableData.value = res.data.data.list;
    total.value = res.data.data.total;
  });
};
const handleSizeChange = val => {
  pageSize.value = val;
  togetProductManager();
};
const handleCurrentChange = val => {
  pageNum.value = val;
  togetProductManager();
};
const departmentList = ref([]);
const togetDepartment = () => {
  getDepartment().then(res => {
    if (res.data.status != 0) {
      return ElMessage.error(res.data.message);
    }
    departmentList.value = res.data.data;
  });
};
//声明周期函数，自动执行初始化
onMounted(() => {
  togetProductManager();
  togetDepartment();
});
</script>

<style scoped lang="scss">
.productManager {
  .content {
    background: #fff;
    .top {
      display: flex;
      justify-content: space-between;
      margin-bottom: 10px;
    }
  }
}
.breadcrumb {
  display: flex;
  margin-bottom: 10px;
}
</style>